package com.edu.ahm.syn;

/**
 *  安全的买票
 *
 *  在 买票 方法 加入 synchronized 保证了安全性
 *
 */
public class SafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();
        Thread thread1 = new Thread(buyTicket,"黄牛1");
        Thread thread2 = new Thread(buyTicket,"黄牛2");
        Thread thread3 = new Thread(buyTicket,"黄牛3");

        // 三个人开始抢票
        thread1.start();
        thread2.start();
        thread3.start();



    }

}

class BuyTicket implements Runnable{
    private int ticketNums = 10;
    boolean flag = true;
    @Override
    public void run() {
        // 买票
        while (flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
    // synchrozied 同步方法 锁的是 this
    public synchronized void buy() throws InterruptedException {
        // 判断是否有票
        if(ticketNums<=0){
            flag = false;
            return;
        }
        // 模拟延时
        Thread.sleep(100);
        // 买票
        System.out.println(Thread.currentThread().getName()+">>>"+ticketNums--);
    }

}